package com.yanqu.road.server.manager.activity.daomu.pvp.rank;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Objects;

public class DaoMuRankListModel {

    private Comparator<DaoMuRank> rankSort = new DaoMuRankSort();

    private LinkedList<DaoMuRank> rankList = new LinkedList<>();

    public DaoMuRankListModel() {

    }

    public DaoMuRankListModel(Comparator<DaoMuRank> rankSort) {
        this.rankSort = rankSort;
    }

    public void rankChange(DaoMuRank rank) {
        synchronized (this) {
            boolean change = false;
            boolean find = false;
            for (DaoMuRank tmpRank : rankList) {
                // 找到了
                if (tmpRank.getUserId() == rank.getUserId()) {
                    tmpRank.setValue(rank.getValue());
                    tmpRank.setParam(rank.getParam());
                    tmpRank.setTime(rank.getTime());
                    change = true;
                    find = true;
                    break;
                }
            }
            if (!find) {
                rankList.add(rank);
                change = true;
            }
            if (change) {
                rankSort();
            }
        }
    }

    public LinkedList<DaoMuRank> getRankList() {
        synchronized (this) {
            return new LinkedList<>(rankList);
        }
    }

    public void setRankList(LinkedList<DaoMuRank> rankList) {
        synchronized (this) {
            this.rankList = rankList;
            rankSort();
        }
    }

    public int getMyRank(long userId) {
        int rank = -1;
        int index = 0;
        synchronized (this) {
            for (DaoMuRank userRank : rankList) {
                if (userRank.getUserId() == userId) {
                    rank = index + 1;
                    break;
                }
                index++;
            }
        }
        return rank;
    }

    /**
     * 排序，记得加锁
     */
    private void rankSort() {
        rankList.sort(rankSort);
    }

}
